#!/usr/bin/perl  -w 
use strict;
use warnings;

#std includes
use POSIX qw(strftime);
use File::Basename;

#ml pkg includes
use MLDBUtils::DBConvert;
use MLDBUtils::DBConnect;
use MLDBUtils::DBCustID;

my $MLPROD_HOME = $ENV{'MLPROD_HOME'};
my $PGNAME=basename($0);
my $PGDIRNAME=dirname($0);
my $PGERR=$PGNAME."[$$]";
my $PGUSER=$ENV{'USER'};
my $PGPWD =$ENV{'PWD'};
if($PGDIRNAME !~ m/^\//) {
  $PGDIRNAME="$PGPWD/$PGDIRNAME";
}




# lock cust schema name from folder path
my $g_dbschema    = undef;    # fetch from the locked path
my $g_mod_ctx     = undef;
my $g_cust_id     = undef;    # query the db to get based on schema name
my $g_hospital_id = 1;        # for now hard coded;

if($PGDIRNAME =~ m/^.*\/cust\/(\w+)\/scripts\/(\w+)(\/.*)?$/) {
  $g_dbschema = $1;
  $g_mod_ctx  = $2;
} else {
  print STDERR "$PGNAME: Unable to get cust context from : <$PGDIRNAME>\n";
  exit 1;
}


# globals
my %args;

my $g_dbbasename="$ENV{USER}";
my $g_dbname=$g_dbbasename . "_db";
my $g_dbuser=$g_dbschema . "_" . $g_dbbasename . "_u";
my $g_dbpasswd = undef;
my $g_in_tbl_name  = $g_dbschema . ".read_recon_t";
my $g_out_tbl_name = $g_dbschema . ".temp_batch_recon_t";
my $g_dbconv;
my $g_dbconn;
my $g_dbcust;
my $g_err;
my $g_exitcode = 0;
my $g_acct_hdr_file = undef;
my $g_batch_acct_hdr_file = undef;
my $g_acct_data_file = undef;
my $g_batch_acct_data_file = undef;
my $g_batch_recv_date=undef;
my $g_batch_run_date=undef;
my $g_batch_acct_file = undef;

#prototypes def here


# do nothing
sub handler_default
{
  my $batch_acct_col_name = shift(@_);
  my $acct_row_hash_ref = shift(@_);
  my $batch_acct_row_hash_ref = shift(@_);

  return 1;
}


sub handler_note
{
  my $batch_acct_col_name = shift(@_);
  my $acct_row_hash_ref = shift(@_);
  my $batch_acct_row_hash_ref = shift(@_);

  # truncate note field to length 120 
  $batch_acct_row_hash_ref->{$batch_acct_col_name} = substr($acct_row_hash_ref->{"note"}, 0, 120);

  return 1;
}

sub handler_date
{
  my $batch_acct_col_name = shift(@_);
  my $acct_row_hash_ref = shift(@_);
  my $batch_acct_row_hash_ref = shift(@_);
  if (length($acct_row_hash_ref->{$batch_acct_col_name}) != 10 ) {
  	$batch_acct_row_hash_ref->{$batch_acct_col_name} = ''; 
  }
  else {
	$batch_acct_row_hash_ref->{$batch_acct_col_name} = $acct_row_hash_ref->{$batch_acct_col_name};
  }
  return 1;

  #my $input_date = shift(@_);
  #my len = length($input_date);
  #if ((len != 8) or (len != 6)){
#	return null;
 # }
 # else {
#	return $input_date;
#  } 

}



# all handlers should be defined above this
sub register_batch_acct_handlers()
{

  $g_dbconv->register_handler("note", \&handler_note);

  # STANDARD HANDLERS - INSERT null VALUES - DO NOT MODIFY THESE LINES
  $g_dbconv->register_handler("seqnum", \&handler_default);
  $g_dbconv->register_handler("recon_ind", \&handler_default);
  $g_dbconv->register_handler("recon_exclude", \&handler_default);
  $g_dbconv->register_handler("recon_full_scenario", \&handler_default);
  $g_dbconv->register_handler("customer_type", \&handler_default);
  $g_dbconv->register_handler("processing_type", \&handler_default);
  $g_dbconv->register_handler("emdeon_ind", \&handler_default);
  $g_dbconv->register_handler("lname", \&handler_default);
  $g_dbconv->register_handler("client_field1", \&handler_default);
  $g_dbconv->register_handler("client_field2", \&handler_default);
  $g_dbconv->register_handler("client_field3", \&handler_default);
  $g_dbconv->register_handler("client_date1", \&handler_default);
  $g_dbconv->register_handler("pat_proc_type", \&handler_default);
  $g_dbconv->register_handler("pat_type", \&handler_default);
  $g_dbconv->register_handler("original_run_date", \&handler_default);
  $g_dbconv->register_handler("first_delivery_date", \&handler_default);
  $g_dbconv->register_handler("service_date_begin", \&handler_default);
  $g_dbconv->register_handler("service_date_end", \&handler_default);
  $g_dbconv->register_handler("charges", \&handler_default);
  $g_dbconv->register_handler("balance", \&handler_default);
  $g_dbconv->register_handler("insurance_desc", \&handler_default);
  $g_dbconv->register_handler("plan_type", \&handler_default);
  $g_dbconv->register_handler("medlytix_note", \&handler_default);
  $g_dbconv->register_handler("validate_ind", \&handler_default);
  $g_dbconv->register_handler("validated_date", \&handler_default);
  $g_dbconv->register_handler("multiple_row", \&handler_default);
  $g_dbconv->register_handler("warning_doublepay", \&handler_default);
  $g_dbconv->register_handler("user_id", \&handler_default);
  $g_dbconv->register_handler("recon_sent_date", \&handler_default);
  $g_dbconv->register_handler("medlytix_ins_type", \&handler_default);

  # data imported into our database
  $g_dbconv->register_handler("date_billed", \&handler_date);
  $g_dbconv->register_handler("paid_date", \&handler_date);
  $g_dbconv->register_handler("date_rejected", \&handler_date);
  $g_dbconv->register_handler("prior_ins_date", \&handler_date);            

}



sub DESTROY
{
  print STDERR "EXIT CLEANUP\n";
  if(defined $g_dbconn) {
    $g_dbconn->disconnect;
  }
}



$g_dbconn = MLDBUtils::DBConnect->new($g_dbname, $g_dbuser, $g_dbpasswd, \$g_err);
if ( ! defined $g_dbconn ) {
  print STDERR "Unable to connect to DB : $g_err\n";
  exit 3;
}

# get hospital id
$g_dbcust = MLDBUtils::DBCustID->new($g_dbconn, \$g_err);
if ( ! defined $g_dbconn ) {
  print STDERR "Unable to get cust db info : $g_err\n";
  exit 4;
}

if(!$g_dbcust->custid_by_name( $g_dbschema, \$g_cust_id )) {
  print STDERR "Unable to get cust id from db : ", $g_dbcust->errstr, "\n";
  exit 4;
}

if(! defined $g_cust_id || ( $g_cust_id eq "" ) || ($g_cust_id <= 0)) {
  print STDERR "Unable to get hospital system id from db for cust : ", $g_dbschema, "\n";
  exit 4;
}


$g_dbconv = MLDBUtils::DBConvert->new
                 (
                   \$g_err,
                   {
                     dbh           => $g_dbconn,
                     in_tbl_name   => $g_in_tbl_name,
                     out_tbl_name  => $g_out_tbl_name,
                     in_hdr_file   => $g_acct_hdr_file,
                     out_hdr_file  => $g_batch_acct_hdr_file,
                     in_data_file  => $g_acct_data_file,
                     out_data_file => $g_batch_acct_data_file,
                   }
                 );

if( !defined $g_dbconv) {
  print STDERR "Unable to convert : ", $g_err, "\n";
  exit 4;
}

register_batch_acct_handlers();

$g_exitcode = !$g_dbconv->convert();



$g_dbconn->commit;

if($g_exitcode) {
  print STDERR "${PGNAME} : conversion failed : $g_dbconv->{errstr}\n";
}

$g_dbconn->disconnect;
$g_dbconn = undef;

exit($g_exitcode);
